package com.demodis.dao.impl;

import java.util.ArrayList;
import java.util.List;

import com.demodis.dao.persSugDaoI;
import com.demodis.domain.TblPersSuggest;
import com.demodis.util.DBUtil;

public class persSugDaoImpl extends BaseDao implements persSugDaoI {

	@Override
	public boolean save(TblPersSuggest tps) {
		String sql = "INSERT INTO TBL_PersSuggest(detperId, deterId, psCont) VALUES(?, ?, ?);";
		int i = 0;
		try {
			conn = DBUtil.getConnection();
			ps = conn.prepareStatement(sql);

			ps.setInt(1, tps.getDetperId());
			ps.setInt(2, tps.getDeterId());
			ps.setString(3, tps.getPsCont());

			i = ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(conn, ps, rs);
		}
		return i == 1 ? true : false;
	}

	@Override
	public boolean isExist(int detPerId, int userId) {
		String sql = "SELECT COUNT(*) FROM TBL_PERSSUGGEST WHERE DETPERID = ? AND DETERID = ?;";
		int i = 0;
		try {
			conn = DBUtil.getConnection();
			ps = conn.prepareStatement(sql);

			ps.setInt(1, detPerId);
			ps.setInt(2, userId);

			rs = ps.executeQuery();
			if(rs.next()) {
				i = rs.getInt(1);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(conn, ps, rs);
		}
		return i >= 1 ? true : false;
	}

	@Override
	public List<TblPersSuggest> get(int userId) {
		String sql = "select * from tbl_perssuggest where psCont != '' and detperId = ?;";
		List<TblPersSuggest> list = new ArrayList<TblPersSuggest>();
		try {
			conn = DBUtil.getConnection();
			ps = conn.prepareStatement(sql);
			ps.setInt(1, userId);
			rs = ps.executeQuery();
			while (rs.next()) {
				TblPersSuggest persSug = new TblPersSuggest();
				persSug.setPsId(rs.getInt("psId"));
				persSug.setDetperId(rs.getInt("detperId"));
				persSug.setDeterId(rs.getInt("deterId"));
				persSug.setPsCont(rs.getString("psCont"));
				list.add(persSug);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(conn, ps, rs);
		}
		return list;
	}

}
